// Loggr::Tools::Thread
// Tools make Loggr be more autonomous.
// By George Ulyanov (c) 2010

#include "Config.h"

#ifndef LOGGR_TOOLS_THREAD_H_
#   include "Thread.h"
#endif

#if defined (LOGGR_WIN32API)
#	include <Windows.h>
#elif defined (LOGGR_OTHER)
#	include <stdlib.h>
#endif
#include <stdexcept>

namespace Loggr
{
    namespace Tools
    {
        struct ThreadData
        {
#if defined (LOGGR_WIN32API)
            HANDLE      m_thread;
#elif defined (LOGGR_OTHER)
#   pragma error "Not implemented"
#endif
        };

        Thread::Thread()
        {
            m_data = new ThreadData();
            if (!m_data)
            {
                throw std::runtime_error("Couldn't initialize Thread::ThreadData.");
            }
#if defined (LOGGR_WIN32API)
            m_data->m_thread = INVALID_HANDLE_VALUE;
#elif defined (LOGGR_OTHER)
#   pragma error "Not implemented"
#endif
        }

        Thread::~Thread() throw()
        {
#if defined (LOGGR_WIN32API)
            if (m_data->m_thread != INVALID_HANDLE_VALUE)
            {
                ::CloseHandle(m_data->m_thread);
            }
#elif defined (LOGGR_OTHER)
#   pragma error "Not implemented"
#endif
            delete m_data;
        }

        void Thread::Start(int (* ptfunc)(void*), void* params)
        {
#if defined (LOGGR_WIN32API)
            m_data->m_thread = ::CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ptfunc, params, 0, 0);
#elif defined (LOGGR_OTHER)
#   pragma error "Not implemented"
#endif
        }

        void Thread::Wait()
        {
#if defined (LOGGR_WIN32API)
            ::WaitForSingleObject(m_data->m_thread, INFINITE);
#elif defined (LOGGR_OTHER)
#   pragma error "Not implemented"
#endif
        }

        void Thread::Waiter(unsigned int ms)
        {
#if defined (LOGGR_WIN32API)
            ::Sleep(ms);
#elif defined (LOGGR_OTHER)
#   pragma error "Not implemented"
#endif
        }
    }
    // namespace Tools
}
// namespace Loggr
